package com.zhiwang.planet.ui

import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.cmcm.cmgame.CmGameSdk
import com.umeng.analytics.MobclickAgent
import com.zhiwang.planet.App
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.di.component.DaggerUserComponent
import com.zhiwang.planet.di.component.UserComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.LogoutEvent
import com.zhiwang.planet.exception.ExpiredException
import com.zhiwang.planet.mvp.v.AuthView
import com.zhiwang.planet.ui.loginv2.WxLoginActivity
import com.zhiwang.planet.util.*
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus

abstract class BaseActivity : AppCompatActivity(), AuthView {

    open fun initInjection() {}

    fun getAppComponent() = (application as App).appComponent

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initInjection()
        //Android 8.0 不允许非全屏Activity固定屏幕方向
        if (Build.VERSION.SDK_INT != 26)
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }

    override fun onError(t: Throwable) {
        if (t is ExpiredException) {
            TokenManager.clearToken()
            CmGameSdk.clearCmGameAccount()
            onAuthExpired()
            if (BuildConfig.DEBUG)
                t?.message?.apply { Toaster.message(this) }

        } else {
            t?.message?.apply { Toaster.message(this) }
        }
    }

    override fun onAuthExpired() {
        EventBus.getDefault().post(LogoutEvent())
//        if (TokenManager.hasPhoneLogged()) {
        //手机号登录过，直接微信登录
            quickStartActivity(WxLoginActivity::class.java)
//        } else
//        //新用户第一次登录
//            quickStartActivity(LoginV2Activity::class.java)
        if (this !is MainActivity)
            suicideAfterTransition()
    }

    override fun onResume() {
        super.onResume()
        if (BuildConfig.DEBUG.not())
            MobclickAgent.onResume(this)
    }


    override fun onPause() {
        super.onPause()
        if (BuildConfig.DEBUG.not())
            MobclickAgent.onPause(this)
    }

    /**
     * 主要是为了方便监听EditText 的输入变化，来控制一些按钮的enable 状态来改变按钮的背景；
     * +由于很多地方都有用到，所以提取到了BaseActivity
     */
    fun observeTextChangeWithTargetButtonEnableStatus(views: Array<EditText>, target: View) {

        val textWatcher = object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)
                views.forEach {
                    if (it.text.isEmpty()) {
                        target.isEnabled = false
                        return
                    }
                }
                target.isEnabled = true
            }
        }

        views.forEach {
            it.addTextChangedListener(textWatcher)
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return super.onSupportNavigateUp()
    }

    private var disposableCollection: ArrayList<Disposable> = ArrayList()

    fun addToDiposable(disposable: Disposable?) {
        if (disposable != null && disposable.isDisposed.not())
            disposableCollection.add(disposable)
    }

    override fun onDestroy() {
        super.onDestroy()
        for (disposable in disposableCollection) {
            if (disposable.isDisposed.not())
                disposable.dispose()
        }
    }

    fun webViewHeader(): Map<String, String> {
        return mapOf(
                Pair("appdevice", "android")
                , Pair("plat", ChannelUtil.getChannel(App.instance))
                , Pair("apptoken", TokenManager.webviewHeaderToken())
                , Pair("appversion", BuildConfig.VERSION_CODE.toString())
                , Pair("Referer", "http://www.shandw.com")
                , Pair("mtype", "xiangguo")
        )
    }


    fun  userComponent(t:AppCompatActivity): UserComponent {
       return DaggerUserComponent.builder()
                .accountModule(AccountModule(t))
                .appComponent(getAppComponent())
                .autoDisposeModule(AutoDisposeModule(t))
                .build()

    }

}
